<script setup>
import { onMounted, ref, watch, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { TooltipComponent, GridComponent } from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { UniversalTransition } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([
  TooltipComponent,
  GridComponent,
  LineChart,
  CanvasRenderer,
  UniversalTransition
])
import { dataSalesDrend } from '@/apis/apis.js'

const dateTimestamp = ref([])
const time = ref([])
const total = ref([])
const echartRef = ref(null)
const echartOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    boundaryGap: true,
    data: []
  },
  yAxis: {
    type: 'value'
  },
  grid: {
    left: '0%',
    right: '0%',
    bottom: '0%',
    containLabel: true
  },
  series: [
    {
      name: '销售额',
      type: 'line',
      data: []
    },
  ],
  color: ['orange']
})
let echart = null

const getData = async () => {
  const data = {}
  if (dateTimestamp.value.length > 0) {
    data.queryTime = dateTimestamp.value
  }
  const res = await dataSalesDrend(data)
  time.value = res.data.time
  total.value = res.data.total
}

const resize = () => {
  if (echart) {
    echart.resize()
  }
}

onMounted(async () => {
  await getData()
  echart = echarts.init(echartRef.value)
  echart.setOption(echartOption.value)
  window.addEventListener('resize', resize)
})

onUnmounted(() => {
  if (echart) {
    echart.dispose()
  }
  window.removeEventListener('resize', resize)
})

watch(time, () => {
  echartOption.value.xAxis.data = time.value
})

watch(total, () => {
  echartOption.value.series[0].data = total.value
})

watch(dateTimestamp, async () => {
  await getData()
  echart.setOption(echartOption.value)
})
</script>

<template>
  <div class="container">
    <div class="title">
      <span>销售额趋势</span>
      <el-date-picker v-model="dateTimestamp" type="daterange" range-separator="至" start-placeholder="开始日期"
        end-placeholder="结束日期" value-format="x" @clear="dateTimestamp = []" />
    </div>
    <div class="content">
      <div ref="echartRef" style="height: 300px;"></div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.container {
  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;

    span {
      width: 25%;
    }
  }
}
</style>
